<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/wellcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商家管理</el-breadcrumb-item>
      <el-breadcrumb-item>修改商家</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="margin-top:20px;">
      <div slot="header" class="clearfix">
        <span>
          <i class="el-icon-menu"></i> 操作面板
        </span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-edit">新增商家</el-button> -->
      </div>
      <!-- 表单部分 -->
      <el-row>
        <el-col :span="8">
          <!--
             属性解释：
              model：存放表单数据的对象
              rules：表单校验规则
          ref：对表单进行重置操作-->
          <el-form label-width="80px" :model="ruleForm" :rules="rules" ref="ruleForm">
            <!-- 商家图片 -->
            <el-form-item label="商家图片" prop="b_img">
              <!-- 
                文件上传组件 
                action:上传文件服务器地址
              -->
              <el-upload
                class="avatar-uploader"
                action="http://localhost:9001/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="ruleForm.b_img" :src="ruleForm.b_img" class="avatar" fit="cover" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- 表单其他信息 -->
            <el-form-item label="商家名称" prop="b_name">
              <el-input type="text" v-model="ruleForm.b_name" placeholder="请输入商家名称" />
            </el-form-item>
            <el-form-item label="商家所供" prop="b_offer">
              <!-- 复选框组件 -->
              <el-checkbox-group v-model="ruleForm.b_offer">
                <el-checkbox label="干净饮用" name="type"></el-checkbox>
                <el-checkbox label="消毒猫砂盆" name="type"></el-checkbox>
                <el-checkbox label="宠物玩具" name="type"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="商家评分" prop="b_score">
              <el-input type="number" v-model="ruleForm.b_score" placeholder="请输入商家评分">
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
            <el-form-item label="寄养价格" prop="b_price">
              <el-input type="number" v-model="ruleForm.b_price" placeholder="请输入寄养价格">
                <template slot="append">元/天</template>
              </el-input>
            </el-form-item>
            <el-form-item label="店铺面积" prop="b_JS">
              <el-input type="text" v-model="ruleForm.b_JS" placeholder="请输入店铺面积">
                <template slot="append">m²</template>
              </el-input>
            </el-form-item>
            <el-form-item label="店铺地址" prop="b_city">
              <el-input type="text" v-model="ruleForm.b_city" placeholder="请输入店铺地址" />
            </el-form-item>
            <el-form-item label="店铺评价" prop="b_feature">
              <el-input type="text" v-model="ruleForm.b_feature" placeholder="请输入店铺评价" />
            </el-form-item>
            <el-form-item label="详细地址" prop="b_city_detail">
              <el-input
                type="textarea"
                v-model="ruleForm.b_city_detail"
                :rows="2"
                placeholder="请输入店铺详细地址"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-check" @click="submitForm('ruleForm')">修改</el-button>
              <el-button
                type="warning"
                icon="el-icon-refresh-right"
                @click="resetForm('ruleForm')"
              >重置</el-button>
              <el-button type="info" icon="el-icon-back" @click="back">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单校验规则
      rules: {
        b_img: [
          { required: true, message: "请选择商家图片", trigger: "change" }
        ],
        b_name: [
          { required: true, message: "请填写商家名称", trigger: "blur" }
        ],
        b_city: [
          { required: true, message: "请填写商家所在城市", trigger: "blur" }
        ],
        b_score: [
          { required: true, message: "请填写商家评分", trigger: "blur" }
        ],
        b_price: [
          { required: true, message: "请填写寄养价格", trigger: "blur" }
        ],
        b_offer: [
          {
            required: true,
            message: "请至少选择一个商家所供",
            trigger: "change"
          }
        ],
        b_JS: [
          { required: true, message: "请填写商家店铺面积", trigger: "blur" }
        ],
        b_feature: [
          { required: true, message: "请填写商家标签", trigger: "blur" }
        ],
        b_city_detail: [
          { required: true, message: "请填写商家店铺详细地址", trigger: "blur" }
        ]
      },
      // 表单数据
      ruleForm: {
        b_id: "",
        // 接收表单数据
        b_img: "", // 图片上传成功后，位于服务器的地址
        b_price: "",
        b_JS: "",
        b_score: "",
        b_feature: "",
        b_city: "",
        b_city_detail: "",
        b_offer: [],
        b_name: ""
      }
    };
  },
  mounted() {
    //console.log(this.$route.query);
    this.getInfo();
  },
  methods: {
    // 返回
    back() {
      this.$router.back();
    },
    // 根据商家id获取商家信息
    getInfo() {
      // 获取传递过来的id
      this.ruleForm.b_id = this.$route.query;
      // 访问服务器获取数据
      this.$http
        .get(`${this.$api.getBusinessById}?b_id=${this.ruleForm.b_id}`)
        .then(res => res?.data)
        .then(res => {
          // 这个then中的res，返回上一个then中的res.data
          console.log("商家信息返回：", res);
          if (res.code == 200) {
            this.ruleForm = res.data;
            // 此时，ruleForm中的b_offer是字符串，但是界面需要数组
            let b_offer = this.ruleForm.b_offer; // a,b,c
            // 将字符串转换为数组
            b_offer = b_offer.split(",");
            // 更新this.ruleForm
            this.$set(this.ruleForm, "b_offer", b_offer);
            console.log("组装this.ruleForm：", this.ruleForm);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    // 提交表单
    submitForm(formName) {
      // 校验表单，提示：校验之前，需要在rules中配置校验规则
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 将商家所供，由数组转换为字符串
          this.$set(this.ruleForm, "b_offer", this.ruleForm.b_offer.toString());
          // 表单校验通过
          console.log("修改商家请求数据：", this.ruleForm);
          this.$http
            .post(this.$api.updatePetBusiness, this.ruleForm)
            .then(res => {
              console.log("修改商家信息返回：", res.data);
              if (res?.data?.code == 200) {
                this.$message.success(res?.data?.msg);
                // 清空表单
                this.resetForm("ruleForm");
                // 跳转网页
                this.$router.replace("/home/businessList");
              } else {
                this.$message.error(res?.data?.msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      //this.ruleForm.b_img = URL.createObjectURL(file.raw);
      this.ruleForm.b_img = file?.response?.data;
      console.log("图片位于服务器的地址：", this.ruleForm.b_img, file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或者PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>